package com.deyuanyun.pic.settings.service.base.impl;

import com.alibaba.fastjson.JSONArray;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.settings.controller.dto.BizMsgThresholdVO;
import com.deyuanyun.pic.settings.controller.dto.base.PipeScheduleVO;
import com.deyuanyun.pic.settings.enumeration.ThresholdType;
import com.deyuanyun.pic.settings.service.base.BizMsgThresholdService;
import com.deyuanyun.pic.settings.service.base.BizThresholdTaskService;
import com.deyuanyun.pic.settings.service.msgtemplate.PipeCyclePushMsg;
import com.deyuanyun.pic.settings.support.utils.CronUtils;
import com.deyuanyun.pic.settings.task.ChkInspAppraiseFailTask;
import com.deyuanyun.pic.settings.task.ChkInspResultFailTask;
import com.deyuanyun.pic.settings.task.ChkRiskInputFailTask;
import com.deyuanyun.pic.settings.task.PipeLineCycleTask;
import com.deyuanyun.pic.settings.task.QuartzConsts;
import com.deyuanyun.pic.settings.task.RiskSystemTask;
import com.deyuanyun.pic.settings.task.SchedulerJob;
import com.deyuanyun.pic.settings.task.util.QuartzManagerUtil;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *  系统默认任务调度初始化service实现类
 *  @author axiao(xj08.dream@gmail.com)
 *  @date 2016-08-04
 *  @version 1.0
 *  Histroy: [修改人][时间][描述]
 */
@Service
public class BizThresholdTaskServiceImpl implements BizThresholdTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BizThresholdTaskServiceImpl.class);

    @Autowired
    private BizMsgThresholdService bizMsgThresholdService;

    @Override
    public void checkClientFailData() {
        if(LOGGER.isInfoEnabled())
            LOGGER.info("开始创建客户端调用接口失败后检查的任务");
        SchedulerJob schedulerJob = new SchedulerJob(QuartzConsts.CLIENT_FAIL_INSPRESULT_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME,
                ChkInspResultFailTask.class, CronUtils.CRON_CLIENT_FAIL_INSP_RESULT_DAY);
        QuartzManagerUtil.addCronJob(schedulerJob);

        SchedulerJob schedulerJob2 = new SchedulerJob(QuartzConsts.CLIENT_FAIL_INSPAPPRAISE_C_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME,
                ChkInspAppraiseFailTask.class, CronUtils.CRON_CLIENT_FAIL_INSP_APPRAISE_DAY);
        QuartzManagerUtil.addCronJob(schedulerJob2);


        SchedulerJob schedulerJob3 = new SchedulerJob(QuartzConsts.CLIENT_FAIL_RISKINPUT_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME,
                ChkRiskInputFailTask.class, CronUtils.CRON_CLIENT_FAIL_RISK_INPUT_DAY);
        QuartzManagerUtil.addCronJob(schedulerJob3);

        if(LOGGER.isInfoEnabled())
            LOGGER.info("创建客户端调用接口失败后检查的任务完成");
    }

    @Override
    public void riskSystemCycle() {
        if(LOGGER.isInfoEnabled())
            LOGGER.info("开始创建风险评价页面风险等级系统周期任务");
        String jobName = QuartzConsts.RISK_SYSTEM_JOB_NAME;
        SchedulerJob schedulerJob = new SchedulerJob(jobName, QuartzConsts.RISK_SYSTEM_TASK_GROUP_NAME, RiskSystemTask.class, CronUtils.CRON_SEVEN_DAY);
        QuartzManagerUtil.addCronJob(schedulerJob);
        if(LOGGER.isInfoEnabled())
            LOGGER.info("创建风险评价页面风险等级系统周期任务完成");
    }

    @Override
    public void pipeCycle(String type) {
        if(LOGGER.isInfoEnabled()) {
            LOGGER.info("开始创建管道周期提醒任务");
            LOGGER.info("当前管道周期的类型为：" + type);
        }
        BizMsgThresholdVO bizMsgThresholdVO = bizMsgThresholdService.queryDataByTypeOne(type);

        if (bizMsgThresholdVO != null) {
            String thresholdContent = bizMsgThresholdVO.getThresholdContent();
            if (!StringUtils.isEmpty(thresholdContent)) {
                List<PipeScheduleVO> scheduleVOs = JSONArray.parseArray(thresholdContent, PipeScheduleVO.class);

                //开始创建任务调度
                for (PipeScheduleVO scheduleVO : scheduleVOs) {
                    if(LOGGER.isInfoEnabled())
                        LOGGER.info("当前管道周期的信息为：" + scheduleVO);

                    String pipeLineId = scheduleVO.getPipeLineId();
                    String beginMileageId = scheduleVO.getBeginMileageId();
                    String endMileageId = scheduleVO.getEndMileageId();
                    String name = pipeLineId + beginMileageId + endMileageId;
                    if (StringUtils.isNotEmpty(name)) {
                        String group;
                        if (Objects.equal(type, ThresholdType.RISK_PIPE_SCHEDULE.getValue())) {
                            group = QuartzConsts.RISK_PIPE_TASK_GROUP_NAME;
                        } else if (Objects.equal(type, ThresholdType.INTERNAL_INSP_PIPE_SCHEDULE.getValue())) {
                            group = QuartzConsts.INSP_TASK_GOURP_NAME;
                        }else if (Objects.equal(type, ThresholdType.INTERNAL_EXTE_PIPE_SCHEDULE.getValue())) {
                            group = QuartzConsts.EXTE_TASK_GOURP_NAME;
                        } else {
                            group = QuartzManagerUtil.DEFAULT_JOB_GROUP_NAME;
                        }
                        if(LOGGER.isInfoEnabled())
                            LOGGER.info("当前管道周期的任务名为：" + name + "，组名为：" + group);

                        Map<String, Object> jobDataMap = new HashMap<String, Object>();
                        jobDataMap.put(PipeCyclePushMsg.SCHEDULE_VO, scheduleVO);
                        jobDataMap.put(PipeCyclePushMsg.PIPE_SCHEDULE, bizMsgThresholdVO);

                        SchedulerJob schedulerJob = new SchedulerJob(name, group, PipeLineCycleTask.class, CronUtils.pipeCronStr(scheduleVO), jobDataMap);
                        QuartzManagerUtil.addCronJob(schedulerJob);
                    }
                }
            }
        }
        if(LOGGER.isInfoEnabled()) {
            LOGGER.info("创建管道周期提醒任务完成");
        }
    }

    @Override
    public void deleteDefaultTask() {
        try {
            JobKey jobKey = JobKey.jobKey(QuartzConsts.CLIENT_FAIL_INSPRESULT_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME);
            JobKey jobKey2 = JobKey.jobKey(QuartzConsts.CLIENT_FAIL_INSPAPPRAISE_C_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME);
            JobKey jobKey3 = JobKey.jobKey(QuartzConsts.CLIENT_FAIL_RISKINPUT_JOB_NAME, QuartzConsts.CLIENT_FAIL_GOURP_NAME);
            JobKey jobKey4 = JobKey.jobKey(QuartzConsts.RISK_SYSTEM_JOB_NAME, QuartzConsts.RISK_SYSTEM_TASK_GROUP_NAME);
            List<JobKey> jobKeys = Lists.newArrayList(jobKey, jobKey2, jobKey3, jobKey4);
            Scheduler scheduler = QuartzManagerUtil.getScheduler();
            Set<JobKey> jobKeySet = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(QuartzConsts.RISK_PIPE_TASK_GROUP_NAME));
            Set<JobKey> jobKeySet2 = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(QuartzConsts.INSP_TASK_GOURP_NAME));
            Set<JobKey> jobKeySet3 = scheduler.getJobKeys(GroupMatcher.jobGroupEquals(QuartzConsts.EXTE_TASK_GOURP_NAME));
            jobKeys.addAll(jobKeySet);
            jobKeys.addAll(jobKeySet2);
            jobKeys.addAll(jobKeySet3);
            QuartzManagerUtil.removeJob(jobKeys);
        } catch (Exception e) {
            LOGGER.error("删除默认任务失败", e);
            throw new RuntimeException(e);
        }
    }
}
